package com.geek.gkpush.framework.retry.registry;

import com.geek.gkpush.framework.dispatch.SpringCtxUtils;
import com.geek.gkpush.framework.retry.RetryMsgHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * <h1>处理重试消息实现类的注册器。</h1><br/>
 *
 * <h1><br/><a href="https://u.geekbang.org/subject/arch3/100614201">Java 业务架构实战营：https://u.geekbang.org/subject/arch3/100614201</a></h1><br/><h1><a href="https://gitee.com/ylimhhmily/BizArchPracticeCamp">Java 业务架构实战营代码地址：https://gitee.com/ylimhhmily/BizArchPracticeCamp</a></h1><br/><h1><a href="https://u.geekbang.org/subject/java4th/1001148?source=app_share">高级 Java 工程体系课 2023 版：https://u.geekbang.org/subject/java4th/1001148?source=app_share</a></h1><br/><h1><a href="https://time.geekbang.org/column/intro/100312101?tab=catalog">Dubbo 源码剖析与实战：https://time.geekbang.org/column/intro/100312101?tab=catalog</a></h1>
 *
 * @author hmilyylimh
 *         ^_^
 * @version 0.0.1
 *         ^_^
 * @date 2023/10/2
 *
 */
@Slf4j
@Component
public class RetryMsgHandlerRegistry {

    private static final Map<String, RetryMsgHandler> SERVICE_MAP = new HashMap<>();

    /**
     * <h2>根据策略模式枚举值查询策略对象。</h2>
     *
     * @param bizType
     * @return
     */
    public static RetryMsgHandler getRetryMsgHandler(String bizType) {
        return getService(bizType);
    }

    /**
     * <h2>根据策略模式枚举值查询策略对象。</h2>
     *
     * @param bizType
     * @return
     */
    public static RetryMsgHandler getService(String bizType) {
        return SERVICE_MAP.get(bizType);
    }

    @EventListener(ContextRefreshedEvent.class)
    public void refresh() {
        Map<String, RetryMsgHandler> serviceMap = SpringCtxUtils.getBeansOfType(RetryMsgHandler.class);
        serviceMap.forEach((bean, service) -> {
            String bizType = StringUtils.uncapitalize(service.getClass().getSimpleName());
            SERVICE_MAP.put(bizType, service);
            log.info("RetryMsgHandlerRegistry, bizType={}", bizType);
        });
    }
}